import axios from 'axios'
import { ElMessage } from 'element-plus'
import { diffTokenTime } from '@/utils/auth'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      if (diffTokenTime()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token 失效了'))
      }
    }
    config.headers.Authorization = localStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

service.interceptors.response.use(
  (response) => {
    if (response.status === 500) {
      return Promise.reject(new Error(response.data.message))
    }
    if (response.status === 200) {
      return response.data.data
    } else {
      if (response.data) {
        ElMessage.error(response.data.message)
        return Promise.reject(new Error(response.data.message))
      }
      return Promise.reject(new Error('服务异常，请联系管理员'))
    }
  },
  (error) => {
    console.log(error.response)
    error.response && ElMessage.error(error.response.data)
    return Promise.reject(new Error(error.response.data.message))
  }
)
export default service

export const getRequest = (url, params) => {
  return service({
    url: url,
    method: 'get',
    params
  })
}

export const putRequest = (url, params) => {
  return service({
    url: url,
    method: 'put',
    data: params
  })
}

export const delRequest = (url, params) => {
  return service({
    url: url,
    method: 'delete',
    data: params
  })
}

export const postRequest = (url, params) => {
  return service({
    url: url,
    method: 'post',
    data: params
  })
}
